package controllers;

import java.util.List;

import javax.persistence.Query;

import models.User;
import play.db.jpa.JPA;
import play.mvc.Controller;

public class Users extends Controller {

	public static void register(String myMail, String myName,
			String myPassword, String confirmPass,
			boolean askpermission) {

		List<User> list = User.findAll();
		list = User.find("email", myMail).fetch(1);
		if (list.size() == 0) {
			User user = new User(myMail, myName, myPassword,askpermission);
			user.save();

			Query query = JPA
					.em()
					.createQuery(
							"DELETE FROM User WHERE email=null AND name=null AND password=null ");
			query.executeUpdate();
		} else
			Application.index();

	}

	public static void logIn(String myMail, String myPassword) {

		List<User> list = User.findAll();
		list = User.find("email", myMail).fetch(1);
		if (list.size() == 1) {
			User user = User.find("byEmail", myMail).first();

			if (myPassword.equals(user.password)) {
				String userId = user.id.toString();
				session.put("userId", userId);

				render(user);
			}
		}

	}
}